package com.biscuit.page.basicservice.design.login.strategy;

import com.alibaba.fastjson.JSON;
import com.biscuit.page.basicservice.api.model.request.authorization.AuthorizationAReq;
import com.biscuit.page.basicservice.design.login.LoginType;
import com.biscuit.page.basicservice.model.entities.mysql.SysUser;
import com.biscuit.page.basicservice.model.enums.LoginTypeEnum;
import com.biscuit.page.basicservice.persistence.dao.UserDao;
import com.biscuit.page.basicservice.utils.BaseExceptionUtil;
import com.biscuit.page.basicservice.utils.MD5Util;
import com.biscuit.page.basicservice.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 密码登录
 *
 * @author biscuit
 * @createTime 2024/5/22 13:51
 */
@Slf4j
@Component
@LoginType(type = LoginTypeEnum.PASSWORD_LOGIN)
public class PasswordLogin implements LoginMoreTypeInterface {

    @Resource
    private UserDao userDao;

    @Override
    public SysUser login(AuthorizationAReq req) {
        log.info("AuthorizationService login loginForPassword start，request -> {}", JSON.toJSONString(req));

        // 根据账号获取用户信息
        SysUser sysUser = this.userDao.getByAccount(req.getAccount());

        // 校验用户是否存在
        BaseExceptionUtil.throwException(Objects.nonNull(sysUser), "账号或密码错误");

        // 密码非对称解密
        String decryptPassword = SecurityUtil.decrypt(req.getPassword());

        // 校验密码
        String encryptPassword = MD5Util.md5(decryptPassword);
        BaseExceptionUtil.throwException(encryptPassword.equals(sysUser.getPassword()), "密码错误");

        log.info("AuthorizationService login loginForPassword end，response -> {}", JSON.toJSONString(sysUser));
        return sysUser;
    }

}
